package com.logicwin.aibala.services.file;

import java.util.concurrent.ConcurrentHashMap;

public final class ImageMemCache<K,V> {
	private ConcurrentHashMap<K, V> firstMap = null;
	private ConcurrentHashMap<K, V> secondMap = null;
	private int myCapacity;
	
	public ImageMemCache(int capacity) {
		this.myCapacity = capacity;
		this.firstMap = new ConcurrentHashMap<K, V>();
		this.secondMap = new ConcurrentHashMap<K, V>(); 
	}
	
	public V get(K k) {
		V ret = this.firstMap.get(k);
		if(null == ret) {
			ret = this.secondMap.remove(k);
			if(null != ret) {
				this.firstMap.put(k, ret);
			}
		}
		return ret;
	}
	
	public void put(K k, V v) {
		if(this.firstMap.size() >= this.myCapacity) {
			this.secondMap.clear();
			this.secondMap.putAll(this.firstMap);
			this.firstMap.clear();
			System.gc();
		}
		this.firstMap.put(k, v);
	}
}
